package com.example.mardan_demo1.service.impl;

import com.example.mardan_demo1.mapper.BgsMapper;
import com.example.mardan_demo1.pojo.*;
import com.example.mardan_demo1.service.BgsService;


import com.example.mardan_demo1.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @Author:买尔旦江 ×@CreateTime: 2024-11-22
 * @Description: 业务逻辑时间
 * @Version: 1.0
 */
@Slf4j
@Service
public class BgsServiceImpl implements BgsService {
    private static final Logger logger = LoggerFactory.getLogger(BgsServiceImpl.class);
    @Autowired
    BgsMapper bgsMapper;
    public Result countLogs(Integer pageSize, Integer pageNum) {
        PageBean<UserReportLog> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<UserReportLog> as = bgsMapper.countLogs();
        Page<UserReportLog> p = (Page<UserReportLog>) as;
        pb.setItems(p.getResult());;
        pb.setTotal(p.getTotal());
        return Result.success(pb);
    }
    public Result guanli_dai_shen(Integer pageSize, Integer pageNum){
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Integer userId = (Integer) userInfo.get("id");
        logger.info("userID:" + userId);
        PageBean<UserReportLog> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        List<UserReportLog> as = bgsMapper.guanli_dai_shen(userId);
        Page<UserReportLog> p = (Page<UserReportLog>) as;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return Result.success(pb);
    }
    @Transactional
    public Result guiHuanShenPi(Integer logId) {
        // 判断用户权限
        Map<String,Object> userInfo = ThreadLocalUtil.get();
        String userRole = userInfo.get("role").toString();
        logger.info("userRole:" + userRole);
        if (!userRole.equals("admin")){
            return Result.error("您不是管理员，无法调用该接口");
        }
        Integer admin_id = (Integer) userInfo.get("id");
        logger.info("admin_id:" + admin_id);
        // 判断报告是否可以归还
        // 判断报告书列表的状态是否为已借阅
        UserReportLog bgsLogInfo = bgsMapper.findOneLogByBgsId(logId);
        if (bgsLogInfo == null){
            return Result.error("无效报告书日志");
        }
        Integer bgsId = Integer.valueOf(bgsLogInfo.getBgs_id());
        logger.info("bgsId:" + bgsId);
        Bgs_list bgsInfo = bgsMapper.findBgsById(bgsId);
        if (bgsInfo == null){
            return Result.error("无效报告书");
        }
        String bgsStatus = bgsInfo.getStatus();
        if (!bgsStatus.equals("3")){
            return Result.error("该报告书未被借阅，无法处理");
        }
        // 验证结束后修改报告书状态
        bgsMapper.updateStatus(bgsInfo.getId(),"0");
        // 修改报告书日志
        String wanChengShijian = LocalDateTime.now().toString();
        bgsMapper.wanChengGuiHuan(logId, admin_id, wanChengShijian);
        return Result.success("处理成功");
    }

    public Result guiHuanShenQingLieBiao(Integer pageSize, Integer pageNum){
        // 权限验证
        Map<String,Object> userInfo = ThreadLocalUtil.get();
        String userRole = userInfo.get("role").toString();
        logger.info("userRole:" + userRole);
        if (!userRole.equals("admin")){
            return Result.error("您不是管理员，无法调用该接口");
        }
        PageBean<UserReportLog> pb = new PageBean<>();
        PageHelper.startPage(pageNum,pageSize);
        // 查询申归还status待审核
        String guiHuanStatus ="待审核";
        List<UserReportLog> as = bgsMapper.guiHuanShenQingLieBiao(guiHuanStatus);
        Page<UserReportLog> p = (Page<UserReportLog>) as;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return Result.success(pb);

    }
    @Transactional
    public Result guiHuanShenQing(Integer logId){
        // 判断用户类型，获取用户id和role
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Integer userId = (Integer) userInfo.get("id");
        logger.info("userId: " + userId);
        String userRole = (String) userInfo.get("role");
        logger.info("userRole: " + userRole);
        if (!userRole.equals("customer")) {
            return Result.error("该用户类型没有权限调用该接口");
        }
        // 找到该日志，判断借阅处理意见是否为1，并且归还处理意见是否为空
        Bgs_log bgs_log = bgsMapper.findLogByLogId(logId);
        logger.info("bgs_log: " + bgs_log);
        if (bgs_log == null) {
            return Result.error("无效报告书日志");
        }
        // 状态为待审核的直接返回该报告书没有被借出去
        if (bgs_log.getStatus().equals("待审核")) {return Result.error("该报告书没有被借出去啊");}
        if (!bgs_log.getJie_yue_chu_li_yi_jian().equals("1") || null != bgs_log.getGui_huan_chu_li_yi_jian()){
            return Result.error("该报告书日志不属于已借阅未归还状态");
        }
        // 校验通过后修改检验报告信息表中的信息，修改日志表中的信息
        // 更新报告书状态为0
        String bgs_id = bgs_log.getBgs_id();
        logger.info("bgs_id: " + bgs_id);
        bgsMapper.updateStatus(Integer.valueOf(bgs_id), "3");
        // 修改日志表，新增用户申请归还时间，归还意见，归还请求类型
        String guiHuanStatus = "待审核";
        String yong_hu_gui_huan_shijian = String.valueOf(LocalDateTime.now());
        String yong_hu_gui_huan_yi_jian = "申请归还";
        bgsMapper.guiHuanShenQing(logId, guiHuanStatus,yong_hu_gui_huan_shijian,yong_hu_gui_huan_yi_jian);

        return Result.success("成功");
    }
    public Result getOwnList(Integer pageSize, Integer pageNum){
        // 获取用户id
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        Integer userId = (Integer) userInfo.get("id");
        logger.info("User ID: {}", userId);
        // 根据用户id查询 借阅处理意见是同意，归还处理意见为空 的报告书列表，联合查询
        PageBean<UserReportLog> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        // 查询
        String message = "1";
        List<UserReportLog> as = bgsMapper.getOwnList(userId, message);
        Page<UserReportLog> p  = (Page<UserReportLog>) as;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return Result.success(pb);
    }

    @Transactional
    public Result handleJieYue(Integer userId, Integer bgsId, Integer bgsLogId, String isReject){
        // 判断是否有效用户
        User user = bgsMapper.findUserById(userId);
        if (user == null || !user.getRole().equals("customer")){
            return  Result.error("无效用户");
        }
        Map<String, Object> adminUser = ThreadLocalUtil.get();
        Integer adminId = (Integer) adminUser.get("id");
        // 判断是否有效报告书
        Bgs_list bgs = bgsMapper.findBgsById(bgsId);
        if(bgs == null || !bgs.getStatus().equals("2")){
            return Result.error("报告书不存在或已被借阅");
        }
        // 判断是否有效申请
        UserReportLog bgs_log = bgsMapper.findOneLogByBgsId(bgsLogId);
        if(bgs_log == null){
            return Result.error("无效申请");
        }
        // 验证通过后 1、修改报告书列表status和updated_at
        LocalDateTime now = LocalDateTime.now();
        String status = "1";
        if (isReject.equals("1")) {
            status = "0";
        }
        // 更新报告书表
        bgsMapper.upDateBgsList(bgsId, now, status);
        // 2、修改日志表中的status为“已借阅” cl_message 为“同意”
        status = "已通过";
        String cl_message = "1";
        if (isReject.equals("1")) {
            status = "已拒绝";
            cl_message = "2";
        }
        // 如果管理员拒绝的话就让这条流程结束：
        // 流程 1 用户借阅申请， 2 管理员处理 同意就到3，不同意就到5  3 用户归还申请   4 管理员处理 同意就到5 不同意就到2  5流程结束
        bgsMapper.updateBgsLog(bgsLogId, now, status, cl_message, adminId);
//        bgsMapper.gengXinJieYueRiZhi(bgsLogId, now, "APPROVED", adminId);
        return Result.success(bgs_log);
    }

    public Result bgs_jieYue_log(Integer bgs_id, Integer pageSize, Integer pageNum) {
        // 查看是否有效报告书id
        Bgs_list bgsInfo = bgsMapper.findBgsById(bgs_id);
        if(bgsInfo == null){
            return Result.error("该报告书不存在");
        }
        // 存在就调取日志, 创建pagebean对象开启分页
        PageBean<UserReportLog> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        // 查询
        List<UserReportLog> as = bgsMapper.findLogByBgsId(bgs_id);
        Page<UserReportLog> p = (Page<UserReportLog>) as;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return Result.success(pb);
    }

    public  Result shenQingLieBiao( Integer pageSize, Integer pageNum){
        // 判断权限，是否为admin用户
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        String userRole = userInfo.get("role").toString();
        if (!userRole.equals("admin")){
            return Result.error("您不是管理员用户");
        }
        // 创建pagebean对象
        PageBean<UserReportLog> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);
        // 查询
        String status = "待审核";
        List<UserReportLog> as = bgsMapper.shenQingJieYueRiZhi(status);
        Page<UserReportLog> p = (Page<UserReportLog>)  as;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return Result.success(pb);
    }
    @Transactional
    public Result jieyue(Integer bgs_id, String j_sq_message){
        // 判断用户权限，是否为customer
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        String userRole = userInfo.get("role").toString();
        Integer userId = (Integer) userInfo.get("id");
        System.out.println(userId);
        if (!userRole.equals("customer")){
            return Result.error("您不是使用用户");
        }
        String userIdStr = String.valueOf(userId);
        // 查看是否有效报告书id
        Bgs_list bgsInfo = bgsMapper.findBgsById(bgs_id);
        if (bgsInfo == null){
            return Result.error("该报告书不存在");
        }
        // 查看是否已被借阅
        if (bgsInfo.getStatus().equals("1") || bgsInfo.getStatus().equals("2")) {
            return Result.error("报告书状态为非可借阅状态");
        }
        // 修改状态为2， 表示别人申请了借阅
        bgsMapper.updateStatus(bgs_id, "2");
        // 修改完成后在借阅日志表中插入一条借阅日志
        LocalDateTime shenQingRiQi = LocalDateTime.now();
        String status = "待审核";
        LocalDateTime now = LocalDateTime.now();
        bgsMapper.xinZengJieYueRiZhi(userIdStr, bgsInfo.getId().toString(), "PENDING", now);
        bgsMapper.createJieYueLog(userIdStr, bgsInfo.getId().toString(), shenQingRiQi, status , j_sq_message, now);
        return Result.success("申请成功，待管理员审核！");
    }

    public Result list(String bgsCode, String bgsName, Integer pageSize, Integer pageNum) {
        // 创建pagebean对象
        PageBean<Bgs_list> pb = new PageBean<>();
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        // 查询
        List<Bgs_list> as = bgsMapper.list(bgsCode, bgsName);
        // 数据列表和总数合并
        Page<Bgs_list> p  = (Page<Bgs_list>) as;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return  Result.success(pb);
    }
}
